Break and Continue
Andersama DEC 27, 2021
Consider the following code:
for (size_t i = 0; i < 100; i++) {
for (size_t j = 0; j < 100; j++) {
if (i > 50 && j > 50)
break;
fmt::print("[{},{}]", i, j);
}
...
}
Now imagine we could communicate to the compiler directly that we intend to exit the loops altogether from the break. Currently we'd have to either a) duplicate the break condition or b) use a goto with a label.
for (size_t i = 0; i < 100; i++) {
size_t j = 0;
for (; j < 100; j++) {
if (i > 50 && j > 50)
break;
fmt::print("[{},{}]", i, j);
}
if (i > 50 && j > 50)
break;
}
for (size_t i = 0; i < 100; i++) {
size_t j = 0;
for (; j < 100; j++) {
if (i > 50 && j > 50)
goto stop_this;
fmt::print("[{},{}]", i, j);
}
}
stop_this:
But here's the tricky bit... technically speaking break
is nothing more than a contextualized goto. A break
statement (in a loop) unconditionally jumps to the exit of a loop. Granted we normally have a condition surrounding it, but the point stands it's not much more than a shorthand for goto
. continue
also is similar, except that it jumps to the increment condition followed in some way or form the loop condition.
Suppose we extend c languages in this way break break
a break statement which "breaks" and then "breaks" immediately again. In order to handle the above for example now we could write.
for (size_t i = 0; i < 100; i++) {
for (size_t j = 0; j < 100; j++) {
if (i > 50 && j > 50)
break break;
fmt::print("[{},{}]", i, j);
}
...
}
But of course, we can do better, we can expand this grammatically to escape however nested our loops (or switch statements) happen to be. EG: break break break
could exit out a loop that was 3 deep. Now we can easily communicate a fairly neat optimization with no additional keywords.
How about this? Suppose we allow break continue
in a similar fashion such that we can communicate a break statement which "breaks" and then "continues" immediately afterwards.
The new c++ grammar would be something like:
break_stmt:
break break_stmt
break_stmt continue
This could effectively allow neater hand written code to communicate the intended flow in a loop without jump threading issues.